/*
 * Copyright (C) 2013 Andreas Stuetz <andreas.stuetz@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jujia.tmall.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jujia.tmall.activity.R;
import com.jujia.tmall.activity.MainActivity;
import com.jujia.tmall.adapter.MainOrderListAdapter;
import com.jujia.tmall.base.BaseFragment;
import com.jujia.tmall.base.SealConst;
import com.jujia.tmall.cache.ServerAddress;
import com.jujia.tmall.cache.StringEluneCallback;
import com.jujia.tmall.entity.OrderItemBaseSource;
import com.jujia.tmall.entity.OrderListSource;
import com.jujia.tmall.ui.EmptyRecyclerView;
import com.jujia.tmall.util.ToolsKit;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.HttpParams;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;


public class OrderListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener,
        View.OnClickListener {

    private static final String ARG_POSITION = "position";

    private int position;
    Context mContext;

    @Bind(R.id.fail_container)
    View emptyView;
    @Bind(R.id.recyclerView)
    EmptyRecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    private MainOrderListAdapter mAdapter;

    private List<OrderListSource> mList = new ArrayList<>();


    public static OrderListFragment newInstance(int position) {
        OrderListFragment f = new OrderListFragment();
        Bundle b = new Bundle();
        b.putInt(ARG_POSITION, position);
        f.setArguments(b);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        position = getArguments().getInt(ARG_POSITION);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.nav_fragment_main, null);
        ButterKnife.bind(this, view);
        mContext = getActivity();
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {

        recyclerView.setEmptyView(emptyView);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new MainOrderListAdapter(mList, getActivity());
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(false);
        recyclerView.setAdapter(mAdapter);
        refreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme));
        refreshLayout.setOnRefreshListener(this);
        mAdapter.setOnLoadMoreListener(this);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {
                new MaterialDialog.Builder(getActivity())
//                            .title(R.string.please_choice)
                        .items(R.array.list_credit_inquiry_choice)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog materialDialog, View view, int index, CharSequence charSequence) {
                                switch (index) {
                                    case 0:
                                        ((MainActivity) getActivity()).sign(mList.get(position).getID(), mList.get(position).getTBID());
                                        break;
//                                    case 1:
//                                        ((MainActivity) getActivity()).startLocation();
//                                        break;
                                }
                            }
                        })
                        .show();

            }
        });
        setRefreshing(false);
        dataRefresh();
    }

    public void dataRefresh(){
        onRefresh();
    }


    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }


    @Override
    public void onRefresh() {
        getData();
    }

    private void getData() {
        com.lzy.okgo.model.HttpHeaders headers = new com.lzy.okgo.model.HttpHeaders();
        HttpParams params = new HttpParams();
        params.put("action", "6");
        params.put("id", getBaseBraceletXml(SealConst.SEALTALK_USERID, ""));


        OkGo.post(ServerAddress.BEAN_UTILCONTROLLER_GETDETAILS).tag(mContext).headers(headers).params(params)
                .dialogIsShow(false)
                .tostIsShow(false)
                .cacheMode(CacheMode.NO_CACHE).execute(new StringEluneCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                Log.e("-------", s + "");
                if (ToolsKit.isStringNotEmpty(s)) {
                    mList.clear();
                    List<OrderItemBaseSource> mListBase = JSON.parseArray(s, OrderItemBaseSource.class);

                    if (mListBase != null && mListBase.size() > 0) {
                        for (int i = 0; i < (mListBase.size() / 10); i++) {
                            int k = 0;
                            OrderListSource mOrderListSource = new OrderListSource();
                            mOrderListSource.setSERVICEDATE(mListBase.get(i * 10 + (k++)).getValue());
                            mOrderListSource.setPHONE(mListBase.get(i * 10 + (k++)).getValue());
                            mOrderListSource.setSIGN(mListBase.get(i * 10 + (k++)).getValue());
                            mOrderListSource.setNAME(mListBase.get(i * 10 + (k++)).getValue());
                            mOrderListSource.setLOGO(mListBase.get(i * 10 + (k++)).getValue());
                            mOrderListSource.setDHSM(mListBase.get(i * 10 + (k++)).getValue());
                            mOrderListSource.setADDRESS(mListBase.get(i * 10 + (k++)).getValue());
                            mOrderListSource.setFYYTIME(mListBase.get(i * 10 + (k++)).getValue());
                            mOrderListSource.setID(mListBase.get(i * 10 + (k++)).getValue());
                            mOrderListSource.setTBID(mListBase.get(i * 10 + (k++)).getValue());
                            mList.add(mOrderListSource);
                        }
                        mAdapter.notifyDataSetChanged();
                        mAdapter.loadMoreEnd();
                        setRefreshing(false);

                    } else {
                        toastFrgBtm("很抱歉，没有获取到数据");
                        setRefreshing(false);
                        mAdapter.loadMoreEnd();

                    }

                } else {
                    mAdapter.loadMoreEnd();
                    setRefreshing(false);
                    toastFrgBtm("数据异常");
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                mAdapter.loadMoreEnd();
                setRefreshing(false);
                toastFrgBtm("数据异常");
            }
        });
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onLoadMoreRequested() {

    }
}